import React from 'react';
import { SafeAreaView, StyleSheet } from 'react-native';
import RootSiblings from 'react-native-root-siblings';
import ToastContainer, { ToastType } from './MessageContainer';

let sibling = new RootSiblings(<SafeAreaView />);
let list: { key: string; content: string; type: ToastType; duration: number; onClose: (() => void) | undefined; }[] = [];

let marginTop: number = 32;

function updateNotice() {
  sibling.update(
    <SafeAreaView style={[styles.container, { marginTop: marginTop }]} pointerEvents='box-none'>
      {list.map(item => <ToastContainer
        key={item.key}
        content={item.content}
        duration={item.duration}
        onClose={() => {
          list.splice(list.findIndex(i => i.key === item.key), 1);
          updateNotice();
          item.onClose && item.onClose();
        }}
        type={item.type}
      />)}
    </SafeAreaView>
  );
}

function notice(content: string, type: ToastType, duration = 2, onClose: (() => void) | undefined) {
  const key = Math.random().toString(16);
  list.push({
    key: key,
    content: content,
    type: type,
    duration,
    onClose,
  })
  updateNotice();
}

const Message = {
  success(content: string, duration?: number, onClose?: () => void) {
    notice(content, 'success', duration, onClose);
  },
  error(content: string, duration?: number, onClose?: () => void) {
    notice(content, 'error', duration, onClose);
  },
  info(content: string, duration?: number, onClose?: () => void) {
    notice(content, 'info', duration, onClose);
  },
  warning(content: string, duration?: number, onClose?: () => void) {
    notice(content, 'warning', duration, onClose);
  },
  loading(content: string, duration?: number, onClose?: () => void) {
    notice(content, 'loading', duration, onClose);
  },
  config(top: number) {
    marginTop = top;
  },
};

const styles = StyleSheet.create({
  container: {
    position: "absolute",
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
    backgroundColor: "transparent",
    alignItems: "center",
    zIndex: 999,
  },
});

export default Message;